import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/publishReplay';
//import 'rxjs/add/operator/refCount';

import { HttpUtils } from '../utils/http-utils';
import { User } from './user.model';

@Injectable()
export class AuthService {

  userInfo:Subject<User> = new BehaviorSubject<User>(null);

  constructor(private http: Http) { }

  signIn ({email, password, rememberMe = 0}) :Observable<{token:string}> {
    return this.http.post('api/sign-in', {email, password, rememberMe})
        .publishReplay(1)
        .refCount()
      .map(HttpUtils.extractData)
      .catch(HttpUtils.handleError)
    ;
    //return observable;
  }

  private setUserInfo(user) {
    this.userInfo.next(user);
  }
  getUserInfo() {
    let observable = this.http.get('api/user')
      .publishReplay(1)
      .refCount()
      .map(HttpUtils.extractData)
      .catch(HttpUtils.handleError)
    ;

    observable.subscribe((user) => this.setUserInfo(user));

    return observable;
  }

  signOut () {
    let observable = this.http.delete('api/sign-out')
        .publishReplay(1)
        .refCount()
        .map(HttpUtils.extractData)
        .catch(HttpUtils.handleError)
      ;

    observable.subscribe((user) => this.setUserInfo(null));

    return observable;
  }
}
